"""
Creation Request Model
创作需求模型 - 存储用户的创作需求和生成参数
"""

import uuid
from enum import Enum

from sqlalchemy import Column, String, DateTime, Integer, Boolean, Text, ForeignKey, JSON, Numeric
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from ..core.database import Base


class ContentType(str, Enum):
    """内容类型枚举"""
    IMAGE = "image"
    VIDEO = "video"
    AUDIO = "audio"
    TEXT = "text"


class RequestStatus(str, Enum):
    """请求状态枚举"""
    PENDING = "pending"           # 等待处理
    PROCESSING = "processing"     # 处理中
    COMPLETED = "completed"       # 已完成
    FAILED = "failed"             # 失败
    CANCELLED = "cancelled"       # 已取消
    TIMEOUT = "timeout"           # 超时


class Priority(str, Enum):
    """优先级枚举"""
    LOW = "low"         # 低优先级 (1-3)
    NORMAL = "normal"   # 普通优先级 (4-6)
    HIGH = "high"       # 高优先级 (7-8)
    URGENT = "urgent"   # 紧急优先级 (9-10)


class CreationRequest(Base):
    """创作请求模型"""

    __tablename__ = "creation_requests"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id = Column(
        UUID(as_uuid=True), 
        ForeignKey("users.id", ondelete="CASCADE"), 
        nullable=False,
        index=True
    )

    # 基本信息
    title = Column(String(200), nullable=True)
    description = Column(Text, nullable=True)
    content_type = Column(String(20), nullable=False, index=True)  # image, video, audio, text
    
    # 主要提示词和参数
    prompt = Column(Text, nullable=False)
    negative_prompt = Column(Text, nullable=True)
    
    # AI提供商和模型
    ai_provider = Column(String(50), nullable=False, default="doubao")  # doubao, ali, openai
    ai_model = Column(String(100), nullable=True)
    
    # 内容特定参数（JSON存储）
    content_parameters = Column(JSON, default=dict)
    
    # 通用生成参数
    width = Column(Integer, nullable=True)
    height = Column(Integer, nullable=True)
    duration = Column(Integer, nullable=True)  # 视频/音频时长（秒）
    fps = Column(Numeric(3, 1), nullable=True)  # 视频帧率
    quality = Column(String(20), default="high")  # low, medium, high
    style = Column(String(50), nullable=True)  # 风格描述
    
    # 参考素材
    reference_image_urls = Column(JSON, default=list)  # 参考图片URL列表
    reference_content_ids = Column(JSON, default=list)  # 参考内容ID列表
    
    # 生成设置
    batch_size = Column(Integer, default=1)  # 批量生成数量
    variations = Column(Integer, default=1)  # 变体数量
    seed = Column(Integer, nullable=True)  # 随机种子
    guidance_scale = Column(Numeric(3, 1), nullable=True)  # 引导系数
    
    # 状态管理
    status = Column(String(20), nullable=False, default="pending", index=True)
    priority = Column(String(20), nullable=False, default="normal", index=True)
    progress = Column(Integer, default=0)  # 进度百分比 (0-100)
    
    # 任务队列相关
    task_id = Column(String(100), nullable=True, index=True)  # 关联的任务ID
    worker_id = Column(String(100), nullable=True)  # 处理的工作节点ID
    
    # 结果统计
    generated_count = Column(Integer, default=0)  # 已生成数量
    successful_count = Column(Integer, default=0)  # 成功数量
    failed_count = Column(Integer, default=0)  # 失败数量
    
    # 错误信息
    error_message = Column(Text, nullable=True)
    error_code = Column(String(50), nullable=True)
    
    # 成本估算
    estimated_cost = Column(Numeric(10, 4), nullable=True)  # 预估成本
    actual_cost = Column(Numeric(10, 4), nullable=True)  # 实际成本
    
    # 时间戳
    created_at = Column(DateTime, default=func.now(), index=True)
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
    scheduled_at = Column(DateTime, nullable=True)  # 计划执行时间
    started_at = Column(DateTime, nullable=True)  # 开始处理时间
    completed_at = Column(DateTime, nullable=True)  # 完成时间
    
    # 过期时间
    expires_at = Column(DateTime, nullable=True)
    
    # 关系
    user = relationship("User", back_populates="creation_requests")
    generated_contents = relationship("GeneratedContent", back_populates="creation_request")
    task_queues = relationship("TaskQueue", back_populates="related_request")
    system_logs = relationship("SystemLog", back_populates="related_request")

    def __repr__(self):
        return f"<CreationRequest(id={self.id}, user_id={self.user_id}, type={self.content_type}, status={self.status})>"

    @property
    def is_completed(self) -> bool:
        """是否已完成"""
        return self.status == RequestStatus.COMPLETED

    @property
    def is_failed(self) -> bool:
        """是否失败"""
        return self.status == RequestStatus.FAILED

    @property
    def is_processing(self) -> bool:
        """是否处理中"""
        return self.status == RequestStatus.PROCESSING

    @property
    def is_pending(self) -> bool:
        """是否等待中"""
        return self.status == RequestStatus.PENDING

    @property
    def success_rate(self) -> float:
        """成功率"""
        if self.generated_count == 0:
            return 0.0
        return (self.successful_count / self.generated_count) * 100

    @property
    def processing_time_seconds(self) -> int:
        """处理时间（秒）"""
        if not self.started_at or not self.completed_at:
            return 0
        return int((self.completed_at - self.started_at).total_seconds())

    def get_content_specific_params(self) -> dict:
        """获取内容特定参数"""
        params = self.content_parameters or {}
        
        # 根据内容类型添加特定参数
        if self.content_type == "image":
            if self.width and self.height:
                params.update({
                    "width": self.width,
                    "height": self.height,
                })
        elif self.content_type == "video":
            if self.duration:
                params["duration"] = self.duration
            if self.fps:
                params["fps"] = float(self.fps)
        elif self.content_type == "audio":
            if self.duration:
                params["duration"] = self.duration
                
        return params

    def get_generation_config(self) -> dict:
        """获取完整的生成配置"""
        config = {
            "prompt": self.prompt,
            "negative_prompt": self.negative_prompt,
            "content_type": self.content_type,
            "ai_provider": self.ai_provider,
            "ai_model": self.ai_model,
            "quality": self.quality,
            "style": self.style,
            "batch_size": self.batch_size,
            "variations": self.variations,
            "seed": self.seed,
            "guidance_scale": float(self.guidance_scale) if self.guidance_scale else None,
            "reference_images": self.reference_image_urls or [],
            "reference_contents": self.reference_content_ids or [],
        }
        
        # 添加内容特定参数
        config.update(self.get_content_specific_params())
        
        return config

    def update_progress(self, progress: int, status: str = None) -> None:
        """更新进度和状态"""
        self.progress = max(0, min(100, progress))
        if status:
            self.status = status

    def mark_as_started(self) -> None:
        """标记为开始处理"""
        self.status = RequestStatus.PROCESSING
        self.started_at = func.now()
        self.progress = 0

    def mark_as_completed(self, successful_count: int = None) -> None:
        """标记为完成"""
        self.status = RequestStatus.COMPLETED
        self.completed_at = func.now()
        self.progress = 100
        if successful_count is not None:
            self.successful_count = successful_count

    def mark_as_failed(self, error_message: str, error_code: str = None) -> None:
        """标记为失败"""
        self.status = RequestStatus.FAILED
        self.completed_at = func.now()
        self.error_message = error_message
        if error_code:
            self.error_code = error_code

    def can_retry(self) -> bool:
        """检查是否可以重试"""
        return self.status in [RequestStatus.FAILED, RequestStatus.TIMEOUT, RequestStatus.CANCELLED]